package com.th.supcom.pds.impl.service.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.framework.exception.BusinessException;
import net.carefx.framework.translate.TranslatorManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.th.supcom.pds.domain.pojo.Office;
import com.th.supcom.pds.domain.pojo.PdsPrescDetailCombine;
import com.th.supcom.pds.domain.pojo.PdsSupply;
import com.th.supcom.pds.domain.pojo.PhamDispensaryConfig;
import com.th.supcom.pds.domain.vo.PatientInfo;
import com.th.supcom.pds.domain.vo.PdsSupplyDetailVO;
import com.th.supcom.pds.domain.vo.PdsSupplyVO;
import com.th.supcom.pds.domain.vo.PhamInfo;
import com.th.supcom.pds.domain.vo.Result;
import com.th.supcom.pds.impl.common.enums.IsNeedCheck;
import com.th.supcom.pds.impl.common.utils.ServerUitls;
import com.th.supcom.pds.impl.manager.PhamInfoManager;
import com.th.supcom.pds.impl.service.internal.chargedpresc.ChargedPrescriptionChain;
import com.th.supcom.pds.impl.service.internal.chargedpresc.ChargedPrescriptionContext;
import com.th.supcom.pds.internal.api.PdsRecipefeeService;
import com.th.supcom.pds.internal.api.PdsSupplyProService;
import com.th.supcom.pds.internal.api.config.PhamDispensaryConfigService;
import com.th.supcom.pds.medicare.api.AdapterEmrPrescriptionService;
import com.th.supcom.pds.medicare.api.AdapterPtsExtOutPatientVisitService;

public class PdsRecipefeeServiceImpl implements PdsRecipefeeService
{
    /**
     * 公司版权信息.
     */
    public static final String copyright = "Copyright 2014, Carefx Corporation";
    /**
     * 日志记录器.
     */
    private static final Logger s_logger = LoggerFactory.getLogger (PdsRecipefeeServiceImpl.class);
    /**
     * 提交路径.
     */
    public static final String SCC_BRANCH = "$URL$";

    /**
     * 提交日期.
     */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /**
     * 最终修改人员.
     */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /**
     * 最终版本号.
     */
    public static final String SCC_REVISION = "$Revision$";
    private AdapterPtsExtOutPatientVisitService m_adapterPtsExtOutPatientVisitService;
    private AdapterEmrPrescriptionService m_adapterEmrPrescriptionService;
    private ChargedPrescriptionChain m_chargedPrescriptionChain;
    private PhamInfoManager m_phamInfoManager;
    private PhamDispensaryConfigService m_phamDispensaryConfigService;
    private PdsSupplyProService m_pdsSupplyProService;
    private TranslatorManager m_translatorManager;

    /**
     * 过滤当前科室不能处理的处方
     * 
     */
    public void setChargedPrescriptionChain (final ChargedPrescriptionChain chargedPrescriptionChain)
    {

        this.m_chargedPrescriptionChain = chargedPrescriptionChain;
    }

    public void setPhamInfoManager (PhamInfoManager phamInfoManager)
    {

        m_phamInfoManager = phamInfoManager;
    }

    public void setTranslatorManager (TranslatorManager translatorManager)
    {

        m_translatorManager = translatorManager;
    }

    public void setAdapterPtsExtOutPatientVisitService (AdapterPtsExtOutPatientVisitService adapterPtsExtOutPatientVisitService)
    {

        m_adapterPtsExtOutPatientVisitService = adapterPtsExtOutPatientVisitService;
    }

    public void setAdapterEmrPrescriptionService (AdapterEmrPrescriptionService adapterEmrPrescriptionService)
    {

        m_adapterEmrPrescriptionService = adapterEmrPrescriptionService;
    }

    public void setPhamDispensaryConfigService (PhamDispensaryConfigService phamDispensaryConfigService)
    {

        m_phamDispensaryConfigService = phamDispensaryConfigService;
    }

    public void setPdsSupplyProService (PdsSupplyProService pdsSupplyProService)
    {

        m_pdsSupplyProService = pdsSupplyProService;
    }

    @Override
    public Result findPrescByPrescNoOrCard (Map <String, Object> inmap)
    {

        PdsRecipefeeServiceImpl.s_logger.debug ("进入findPrescByPrescNoOrCard方法,入参:inmap:{}", new Object[]
        { inmap });
        inmap.put ("type", "1");
        final Result result = new Result ();
        List <PdsSupplyVO> pdsSupplys = m_adapterEmrPrescriptionService.findApplyAndPresc (inmap);
        if (pdsSupplys.isEmpty ())
        {
            return null;
        }
        ServerUitls.checkFlag (pdsSupplys);
        // 过滤通过刷卡得到的收费处方
        if ((Integer) inmap.get ("flag") == 2)
        {
            for (int i = pdsSupplys.size () - 1; i >= 0; i--)
            {
                PdsSupply pdsSupply = new PdsSupply ();
                pdsSupply.setPrescNo (pdsSupplys.get (i).getPrescNo ());
                // 过滤掉已经收费的处方
                if (ServerUitls.checkPrescCharge (pdsSupply))
                {
                    pdsSupplys.remove (i);
                    continue;
                }
                // 过滤不合格的处方
                if ("0".equals (pdsSupplys.get (i).getCheckFlag ()))
                {
                    pdsSupplys.remove (i);
                }
            }
        }
        if ((Integer) inmap.get ("flag") == 1)
        {
            // 通过PTS得到患者信息
            PdsSupplyVO vo = pdsSupplys.get (0);
            Long patientVisitId = vo.getOutpVisitId ();
            String patienId = vo.getPatientId ();
            Integer prescSource = vo.getPrescSource () == null ? 0 : vo.getPrescSource ();
            final PatientInfo patientInfo = m_adapterPtsExtOutPatientVisitService.getPatientInfo (patientVisitId, prescSource, patienId);
            result.setPatientInfo (patientInfo);
        }
        final List <PdsSupplyVO> pdsSupplyList = new ArrayList <PdsSupplyVO> ();
        // 查出当前科室的执行范围（全局还是局部）
        String dispensaryCode = (String) inmap.get ("dispensaryCode");
        PhamDispensaryConfig phamDispensaryConfig = new PhamDispensaryConfig ();
        phamDispensaryConfig.setPhamDispensaryCode (dispensaryCode);
        PhamDispensaryConfig config = m_phamDispensaryConfigService.findPhamDispensaryConfigByExample (phamDispensaryConfig).get (0);
        String phamType = config.getphamType ();
        int searchRange = config.getSearchRange ();
        if (searchRange == 0)
        {
            for (PdsSupplyVO pdsSupplyVO : pdsSupplys)
            {
                if (dispensaryCode.equals (pdsSupplyVO.getOrgIdExec ()))
                {
                    pdsSupplyList.add (pdsSupplyVO);
                }
            }
        }
        else
        {
            for (PdsSupplyVO pdsSupplyVO : pdsSupplys)
            {
                if (phamType.equals (pdsSupplyVO.getPrescClassfication ().toString ()))
                {
                    pdsSupplyList.add (pdsSupplyVO);
                }
            }
        }
        result.setPdsSupplyVOs (pdsSupplyList);
        return result;
    }

    @Override
    public Map <String, Object> recipeFee (final List <PdsSupplyVO> pdsSupplys, final List <PdsSupplyDetailVO> pdsSupplyDetails, Map <String, Object> map)
    {
        ChargedPrescriptionContext m_context;
        PdsRecipefeeServiceImpl.s_logger.debug ("进入persistentData方法,入参:pdsSupplys:{},pdsSupplyDetails:{},map:{}", new Object[]
        { pdsSupplys, pdsSupplyDetails, map });
        m_context = new ChargedPrescriptionContext ();
        m_context.setPdsSupplyDetails (pdsSupplyDetails);
        m_context.setMap (map);
        m_context.setPdsSupplys (pdsSupplys);
        return m_chargedPrescriptionChain.exeucte (m_context);
    }

    @Override
    public List <PdsSupplyDetailVO> findPrescDetailByPrescNo (PdsSupplyVO pdsSupplyVo, String currentDispensary)
    {
        s_logger.debug ("进入findPrescDetailByPrescNo方法,入参:pdsSupplyVo:{},currentDispensary:{}", new Object[]
        { pdsSupplyVo, currentDispensary });
        Map <String, Object> inmap = new HashMap <String, Object> ();
        inmap.put ("id", pdsSupplyVo.getPrescId ());
        inmap.put ("type", "1");
        inmap.put ("prescNo", pdsSupplyVo.getPrescNo ());
        List <PdsSupplyDetailVO> pdsSupplyDetailVOs = m_adapterEmrPrescriptionService.findApplyAndDetailed (inmap);
        if (pdsSupplyDetailVOs.isEmpty ())
        {
            return pdsSupplyDetailVOs;
        }
        Double totalPrice = 0.0;
        for (PdsSupplyDetailVO pdsSupplyDetailVO : pdsSupplyDetailVOs)
        {
            // 查出药品单价
            Map <String, Object> params = new HashMap <String, Object> ();
            params.put ("phamStdCode", pdsSupplyDetailVO.getPhamStdCode ());
            Double retailPrice = m_phamInfoManager.getPhamBasicInfoByMap (params).getRetailPrice ();
            Double costs = retailPrice * pdsSupplyDetailVO.getUnitQty ();
            totalPrice += costs;
            pdsSupplyDetailVO.setCosts (costs);
            pdsSupplyDetailVO.setPackagePrice (retailPrice);
            // 设置供药药房
            pdsSupplyDetailVO.setPerformedBy (pdsSupplyVo.getOrgIdExec ());
            pdsSupplyDetailVO.setOrderedBy (pdsSupplyVo.getOrderedBy ());
            // 药品库存检查
            PdsPrescDetailCombine pdsPrescDetailCombine = new PdsPrescDetailCombine ();
            pdsPrescDetailCombine.setPerformedBy (pdsSupplyDetailVO.getPerformedBy ());
            pdsPrescDetailCombine.setPhamCode (pdsSupplyDetailVO.getPhamStdCode ());
            int stock = findDrugStockByExample (pdsPrescDetailCombine);
            if ((pdsSupplyDetailVO.getQtySum () == null ? 0 : pdsSupplyDetailVO.getQtySum ()) > stock)
            {
                // 库存不足打上库存不足标记
                pdsSupplyDetailVO.setStockFlag ("0");
            }
            // 药品批次检查
            PhamInfo phamInfo = findDrugBatchFlagByCode (pdsPrescDetailCombine);
            String batchFlag = null;
            if (phamInfo != null)
            {
                batchFlag = phamInfo.getBatchNumberManagerFlag ();
                // 得到药品的摆药方式
                pdsSupplyDetailVO.setPutDrugMode (phamInfo.getPutDrugMode ());
            }
            if ("1".equals (batchFlag))
            {
                // 需要批次管理 ，给个建议批次号,查询批次号
                Map <String, Object> map = new HashMap <String, Object> ();
                map.put ("performedBy", pdsSupplyDetailVO.getPerformedBy ());
                map.put ("phamStdCode", pdsSupplyDetailVO.getPhamStdCode ());
                final String batchNumber = m_phamInfoManager.findDrugBatchNumber (map).get (0);
                pdsSupplyDetailVO.setPhamBatchNumber (batchNumber);
            }

        }
        for (PdsSupplyDetailVO pdsSupplyDetailVO2 : pdsSupplyDetailVOs)
        {
            if (!"1".equals (pdsSupplyVo.getCheckFlag ()) && IsNeedCheck.Need.getEnumCode ().equals (ServerUitls.checkPhamsToxicology (pdsSupplyDetailVOs)))
            {
                pdsSupplyDetailVO2.setCheckFlag (IsNeedCheck.Need.getEnumCode ());
            }
            pdsSupplyDetailVO2.setTotalPrice (totalPrice);
        }
        // 药品
        return m_translatorManager.translate (pdsSupplyDetailVOs);
    }

    @Override
    public Integer findDrugStockByExample (final PdsPrescDetailCombine pdsPrescDetailCombine)
    {
        PdsRecipefeeServiceImpl.s_logger.debug ("进入findDrugStockByExample方法,入参:pdsPrescDetailCombine:{}", new Object[]
        { pdsPrescDetailCombine });
        Integer stock = 0;
        try
        {
            stock = m_phamInfoManager.findDrugStockByExample (pdsPrescDetailCombine);
        }
        catch (final Exception e)
        {
            PdsRecipefeeServiceImpl.s_logger.error (e.getMessage ());
            throw new BusinessException ("库存查询出现异常，请与计算机中心联系", e);
        }
        return stock == null ? 0 : stock;

    }

    private PhamInfo findDrugBatchFlagByCode (final PdsPrescDetailCombine pdsPrescDetailCombine)
    {
        PdsRecipefeeServiceImpl.s_logger.debug ("进入findDrugBatchFlagByCode方法,入参pdsPrescDetailCombine:{}", pdsPrescDetailCombine);
        PhamInfo phamInfo = null;
        try
        {
            phamInfo = m_phamInfoManager.findPPTBy (pdsPrescDetailCombine);
        }
        catch (final Exception e)
        {
            PdsRecipefeeServiceImpl.s_logger.error ("查询批次号出错,请联系计算机中心", e);
            throw new BusinessException ("查询药品属性出错", e);
        }
        return phamInfo;
    }

    @Override
    public List <Office> findExecutiveOffice (PdsPrescDetailCombine pdsPrescDetailCombine)
    {

        return m_phamInfoManager.findExecutiveOffice (pdsPrescDetailCombine);

    }

    @Override
    public void modifyWindows (List <PdsSupplyVO> pcList, Long window, String currentDispensary)
    {
        s_logger.debug ("进入modifyWindows方法,入参:pcList:{},currentDispensary:{}", new Object[]
        { pcList, currentDispensary });
        Map <String, Object> map = new HashMap <String, Object> ();
        map.put ("list", pcList);
        map.put ("windId", window);
        map.put ("dispensaryCode", currentDispensary);
        m_pdsSupplyProService.modifyBatchSupplyWindow (map);

    }

}
